<template>
  <div class="chart-container" ref="chartContainer"></div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'LineChart',
  props: {
    chartData: {
      type: Object,
      default: () => ({
        labels: [],
        datasets: []
      })
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      handler(newVal) {
        this.updateChart(newVal)
      },
      deep: true
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chartContainer)
      this.updateChart(this.chartData)
    },
    updateChart(data) {
      if (!this.chart) return

      const option = {
        title: {
          text: '收支趋势'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: data.datasets.map(dataset => dataset.label)
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.labels
        },
        yAxis: {
          type: 'value'
        },
        series: data.datasets.map(dataset => ({
          name: dataset.label,
          type: 'line',
          data: dataset.data,
          smooth: true,
          showSymbol: false,
          areaStyle: {
            opacity: 0.1
          }
        }))
      }

      this.chart.setOption(option)
    },
    setOptions(data) {
      this.updateChart(data)
    }
  }
}
</script>

<style lang="scss" scoped>
.chart-container {
  width: 100%;
  height: 350px;
}
</style>